<template>
  <basic-container>
    <avue-crud ref="crud"
               :option="option"
               v-model:page="page"
               :table-loading="loading"
               @on-load="onLoad"
               @row-update="rowUpdate"
               @row-del="rowDel"
               @refresh-change="refreshChange"
               @search-reset="searchChange"
               @search-change="searchChange"
               @selection-change="selectionChange"
               :data="data">
      <template #menu-left="{type,size}">
        <el-button type="primary"
                    :size="size"
                   icon="el-icon-plus"
                   @click="handleAdd">新增
        </el-button>
        <el-button type="success"
                   :size="size" :disabled="multiple"
                   icon="el-icon-position"
                   @click="handleBatchDispatch">批量派工
        </el-button>
      </template>
      <template #status="{ size, row, index }">
        <el-tag :type="tagStatus(row.status)"
                :size="size">{{ row.$status }}</el-tag>
      </template>
      <template #isUrgent="{ size, row, index }">
        <el-tag :type="tagIsUrgent(row.isUrgent)"
                :size="size">{{ row.$isUrgent }}</el-tag>
      </template>
      <template #menu="{ size, row, index }">
        <el-link type="primary"
                   :size="size" :underline="false"
                   icon="el-icon-edit" style="margin-right: 10px"
                   @click="handleEdit(row)">编 辑
        </el-link>
        <el-link type="primary"
                 :size="size" :underline="false"
                 icon="el-icon-delete" style="margin-right: 10px"
                 @click="rowDel(row)">删 除
        </el-link>
        <el-link type="primary"
                 :size="size" :underline="false"
                 icon="el-icon-position" style="margin-right: 10px"
                 @click="handleDispatch(row)">排 工
        </el-link>
        <el-link type="primary"
                 :size="size" :underline="false"
                 icon="el-icon-close" style="margin-right: 10px"
                 @click="handleClose(row)">中 止
        </el-link>
        <el-link type="primary"
                 :size="size" :underline="false"
                 icon="el-icon-view" style="margin-right: 10px"
                 @click="handleView(row)">详 情
        </el-link>
      </template>
    </avue-crud>
    <el-dialog v-model="dialog" :title="dialogTitle" width="80%" append-to-body    class="avue-dialog">
      <avue-form :option="formOption" v-model="form"  @submit="rowSave" ref="formRef">
        <template #name="{row}">{{row.name}}</template>
        <template #productCateName="{row}">{{row.productCateName}}</template>
        <template #craftName="{row}">{{row.craftName}}</template>
        <template #specification="{row}">{{row.specification}}</template>
        <template #unit="{row}">{{row.unit}}</template>
        <template #rate="{row}">{{row.rate}}</template>
        <template #craft="{row}">{{row.craft}}</template>
      </avue-form>
    </el-dialog>
    <el-dialog v-model="dispatchOpen" title="派工" width="80%" append-to-body    class="avue-dialog">
      <avue-form :option="dispatchOpenOption" v-model="dispatchForm" :key="reload"  @submit="dispatchSave" ref="dispatchRef">
        <template v-for="(item,index) in dispatchOpenOption.column.filter(cite => cite.model === 'comm')" #[item.prop]="{value}" :key="index">
          <avue-crud :data="value"
                     :option="dispatchTableOption">
            <template #dispatchNumberNow="scope">
              <el-input-number v-model="scope.row.dispatchNumberNow" placeholder="请输入本次派工数量" min="0" :max="scope.row.unProducedNumber"></el-input-number>
            </template>
          </avue-crud>
        </template>
      </avue-form>
      <div class="avue-dialog__footer" style="text-align:center">
        <el-button @click="dispatchSave" type="primary">确 定</el-button>
        <el-button @click="dispatchOpen=false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script >
import {addPlanOrder, delPlanOrder, listPlanOrder, updatePlanOrder} from "/@/api/produce/planOrder";
import {reactive, ref, toRefs,h} from "vue";
import useCurrentInstance from "/@/utils/useCurrentInstance";
import {getProductInfo, listProduct} from "../../api/base/product";
import {addDispatch, getPlanOrderDetails} from "../../api/produce/planOrder";
export default {
  name: "planOrder",

  setup(props){
    const { proxy } = useCurrentInstance();
    const reload = ref(Math.random());

    const option = ref({
      searchMenuSpan: 6,
      tip: false,
      border: true,
      index: false,
      viewBtn: false,
      selection: true,
      addBtn:false,
      editBtn:false,
      delBtn:false,
      searchLabelWidth:100,
      excelBtn:false,
      labelWidth:120,
      align: 'center',
      column: [

        {
          label: '任务单编码',search: true,
          prop: "encode",
          width: 150,
        },

        {
          label: 'ERP编码',
          prop: "erpEncode",
          width: 150,display: false,
        },

        {
          label: '商品种数',
          prop: "numberKinds",
          width: 150,display: false,
        },

        {
          label: '计划总数',
          prop: "planProduceTotal",
          width: 150,display: false,
        },

        {
          label: '已生产',
          prop: "producedNumber",
          width: 150,display: false,
        },

        {
          label: '未生产',
          prop: "noProducedNumber",
          width: 150,display: false,
        },

        {
          label: '任务单状态',
          prop: "status",search: true,
          width: 150,display: false,
          type: 'select',
          dicData: [
            {
              label: '待派工',
              value: '0'
            },
            {
              label: '派工中',
              value: '1'
            },
            {
              label: '已完成',
              value: '2'
            }
          ],
          dataType: 'number',
        },

        {
          label: '审核结果',
          prop: "auditStatus",display: false,
          width: 150,
        },

        {
          label: '加急标志',
          prop: "isUrgent",
          width: 150,
          dataType: 'number',
          dicData: [
            {
              label: '加急',
              value: 1
            },
            {
              label: '普通',
              value: 0
            }
          ]
        },

        {
          label: '录单人',
          prop: "applicantUserName",search: true,
          width: 150,display: false,
        },


        {
          label: '审批人',
          prop: "approvalUserName",search: true,
          width: 150,display: false,
        },



        {
          label: '录入/更新时间',
          prop: "updateTime", minWidth: 200,
          format: 'YYYY-MM-DD HH:mm:ss',
          type: 'date', display: false,
          search:true,searchRange:true,
          searchLabelWidth: 120,
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },
      ]
    });
    const formOption = ref({
      labelWidth:130,

      column: [

        {
          label: '任务单编码',
          prop: "encode",
          width: 150,
        },
        {
          label: '是否加急',
          prop: "isUrgent",
          width: 150,
          type:'radio',
          dicData: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ],
          value: 0,
          dataType: 'number',
        },

        {
          label: '生产任务单明细',
          prop: "list",
          span:24,
          type: 'dynamic',
          children: {
            align: 'center',
            headerAlign: 'center',
            height: 300,
            rowAdd: (done) => {
              done();
            },
            rowDel: (row, done) => {
              done();
            },
            column: [
              {
                minWidth: 200,
                label: '商品编码',
                prop: 'productId',
                type: 'table',
                children: {
                  border: true, searchMenuSpan: 6,
                  column: [
                    {
                      label: '商品编码',
                      prop: "encode", minWidth: 150, search: true
                    },
                    {
                      label: '商品名称',
                      prop: "name", minWidth: 150, search: true
                    },

                    {
                      label: '商品类型',
                      prop: "productCateName", minWidth: 150,
                    },
                    {
                      label: '规格型号',
                      prop: "specification", minWidth: 150,
                    },
                    {
                      label: '单位',
                      prop: "unit", minWidth: 150,
                    },
                    {
                      label: '工艺路线',
                      prop: "craftName", minWidth: 150,
                    },

                  ],
                },
                formatter: (row) => {
                  if (!row.name) return '';
                  return row.name;
                },
                onLoad: ({page, value, data}, callback) => {
                  console.log({page, value, data},"onLoad")
                  if (value) {
                    let id = value;
                    if (Array.isArray(value) && value.length > 0) {
                      id = value[0];
                    }
                    getProductInfo( id).then(res => {
                      if (form.value.list){
                        form.value.list.forEach(item=>{
                          if (item.productId == id){
                            item.craftName = res.data.craftName;
                            item.name = res.data.name;
                            item.productCateName = res.data.productCateName;
                            item.unit = res.data.unit;
                            item.specification = res.data.specification;
                          }
                        })
                      }
                      callback(res.data);
                    })

                    return;
                  }
                  listProduct(Object.assign({page: page.currentPage, limit: page.pageSize,}, data))
                      .then(res => {
                        const resData = res.data;
                        callback({
                          total: resData.total,
                          data: resData.list,
                        })
                      })
                },
                props: {
                  label: 'name',
                  value: 'id'
                },
              },
              {
                minWidth: 200,
                label: '商品名称',
                prop: 'name'
              },
              {
                minWidth: 200,
                label: '商品类型',
                prop: 'productCateName'
              },
              {
                minWidth: 200,
                label: '规格型号',
                prop: 'specification'
              },
              {
                minWidth: 80,
                label: '单位',
                prop: 'unit'
              },
              {
                minWidth: 200,
                label: '计划生产数量',
                prop: 'planProduceTotal',
                change: function ({row,value}) {
                  extracted(row);
                  let planProduceTotal = 0;
                  form.value.list.forEach(item=>{
                    planProduceTotal =planProduceTotal + Number(item.planProduceTotal || 0)
                  })
                  form.value.planProduceTotal = planProduceTotal;
                }
              },
              {
                minWidth: 200,
                label: '参考生产数量',
                prop: 'referenceProduceTotal',
                change: function ({row,value}) {
                  extracted(row);
                  let referenceProduceTotal = 0;
                  form.value.list.forEach(item=>{
                    referenceProduceTotal =referenceProduceTotal + Number(item.referenceProduceTotal || 0)
                  })
                  form.value.referenceProduceTotal = referenceProduceTotal;
                }
              },
              {
                minWidth: 100,
                label: '备损率',
                prop: 'rate',
                value: 1
              },
              {
                minWidth: 200,
                label: '工艺路线',
                prop: 'craftName'
              },
              {
                minWidth: 200,
                label: '计划生产日期',
                prop: 'planProduceTime',
                type: 'date',valueFormat: 'YYYY-MM-DD',
              },{
                minWidth: 200,
                label: '计划完工日期',
                prop: 'planFinishTime',   type: 'date',valueFormat: 'YYYY-MM-DD',
              },
              {
                minWidth: 200,
                label: '交货日期',
                prop: 'deliveryTime',
                type: 'date',  valueFormat: 'YYYY-MM-DD',
              },

            ]
          },
        },
        {
          label: '计划生产总数',
          prop: "planProduceTotal",
          width: 150,
          disabled: true,
          value:0
        },
        {
          label: '参考生产总数',
          prop: "referenceProduceTotal",
          width: 150,
          disabled: true,
          value:0
        },

      ]
    });

    const dispatchTableOption = ref({
      labelWidth:130,
      index: true,
      border:true,
      align: 'center',
      menu: false,
      header:false,
      indexLabel: '序号',
      indexWidth: 80,
      column: [

        {
          minWidth: 200,
          label: '商品编码',
          prop: 'productEncode',
        },
        {
          minWidth: 200,
          label: '商品名称',
          prop: 'productName'
        },
        {
          minWidth: 200,
          label: '商品类型',
          prop: 'productType'
        },
        {
          minWidth: 200,
          label: '规格型号',
          prop: 'specification'
        },
        {
          minWidth: 80,
          label: '单位',
          prop: 'unit'
        },
        {
          minWidth: 200,
          label: '派工数量',
          fixed: 'right',
          prop: 'dispatchNumberNow',
        },
        {
          minWidth: 200,
          label: '未派工数量',
          prop: 'unDispatchNumber',
        },
        {
          minWidth: 200,
          label: '计划生产数量',
          prop: 'planProduceTotal',
        },
        {
          minWidth: 200,
          label: '参考生产数量',
          prop: 'referenceProduceTotal',

        },
        {
          minWidth: 100,
          label: '备损率',
          prop: 'lossRecoveryRatio',
          value: 1
        },
        {
          minWidth: 200,
          label: '工艺路线',
          prop: 'craftName'
        },
        {
          minWidth: 200,
          label: '计划生产日期',
          prop: 'planProduceTime',
          type: 'date',valueFormat: 'YYYY-MM-DD',
        },{
          minWidth: 200,
          label: '计划完工日期',
          prop: 'planFinishTime',   type: 'date',valueFormat: 'YYYY-MM-DD',
        },
        {
          minWidth: 200,
          label: '交货日期',
          prop: 'deliveryTime',
          type: 'date',  valueFormat: 'YYYY-MM-DD',
        }

      ]
    });


    const dispatchOpenOption = ref({
      labelWidth:130,
      menuBtn:false,
      column: [],
    });
    const loading = ref(true);
    const dialog = ref(false);
    const dispatchOpen = ref(false);
    const multiple = ref(true);
    const dialogTitle = ref('');
    const data = ref([]);
    const crud = ref();
    const dispatchRef = ref(null);
    const formRef = ref(null);
    const selectionList = ref([]);
    const queryParams = ref({});
    const form = ref({});
    const dispatchForm = ref({});
    const page = ref({
      pageSize: 10,
      currentPage: 1,
      total: 0

    })
    const onLoad = (pages, params = {}) => {
      loading.value = true;
      listPlanOrder(Object.assign({ page: pages.currentPage,
        limit: pages.pageSize,},params, queryParams.value)).then(res => {
        const resData =  res.data;
        page.value.total = resData.total;
        data.value = resData.list;
        loading.value = false;
        selectionClear();
      })
    }
    const selectionClear = () => {
      selectionList.value = [];
    }
    const rowSave = (row, done) => {
      addPlanOrder(row).then(() => {
        done();
        dialog.value = false;
        onLoad(page.value);
        proxy.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        done();
      });
    }
    const rowUpdate = (row, index, done, loading) => {
      updatePlanOrder(row).then(() => {
        done();
        onLoad(page.value);
        proxy.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    }
    const rowDel = (row) => {
      proxy.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return delPlanOrder(row);
          })
          .then(() => {
            onLoad(page.value);
            proxy.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    }
    const refreshChange = () => {
      onLoad(page.value, queryParams.value);
    }
    const searchChange = (params, done) => {
      page.currentPage = 1;
      onLoad(page.value, params);
      done();
    }
    const handleAdd = ()=>{
      dialog.value = true;
      dialogTitle.value = '新增';
      form.value = {};
      console.log(formRef)
      if (formRef.value){
        formRef.value.resetForm();
      }
      formOption.value.detail = false;
      formOption.value.menuBtn = true;
    }
    function extracted(row) {
      let planProduceTotal = Number(row.planProduceTotal || 0);
      let referenceProduceTotal = Number(row.referenceProduceTotal || 0);
      if (referenceProduceTotal == 0 && planProduceTotal == 0) {
        row.rate = 1
      } else {
        row.rate = Number(referenceProduceTotal / planProduceTotal).toFixed(2);
      }
    }
    const handleEdit = (row)=>{

      console.log(row)
      let list = [];
      let params = {id: row.id ,encode:row.encode};
      list.push(params);
      formOption.value.detail = false;
      formOption.value.menuBtn = true;
      getPlanOrderDetails({list:list}).then(res => {
        console.log(res.data)
        dialog.value = true;
        dialogTitle.value = '修改';
        form.value = row;
        if (res.data.length > 0) {
          let resData = res.data[0];
          form.value.list = resData.list;
        }

      })

    }
    const handleView = (row)=>{

      let list = [];
      let params = {id: row.id ,encode:row.encode};
      list.push(params);
      formOption.value.detail = true;
      formOption.value.menuBtn = false;
      getPlanOrderDetails({list:list}).then(res => {
        dialog.value = true;
        dialogTitle.value = '详情';
        form.value = row;
        if (res.data.length > 0) {
          let resData = res.data[0];
          form.value.list = resData.list;
        }

      })

    }
    const tagStatus = (status)=>{
      if (status == 0) {
        return 'info'
      }else if (status == 1) {
        return 'success'
      }else if (status == 2) {
        return 'danger'
      }
    }
    const tagIsUrgent = (status)=>{
      if (status == 0) {
        return 'info'
      }else if (status == 1) {
        return 'danger'
      }
    }
    const handleClose = ()=>{
      proxy.$confirm("确定将选择数据中止?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return delPlanOrder(row);
          })
          .then(() => {
            onLoad(page.value);
            proxy.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    }
    const handleDispatch = (row)=>{
      let list = [];
      let params = {id: row.id ,encode:row.encode};
      list.push(params);
      postGetPlanOrderDetails(list);

    }
    const postGetPlanOrderDetails = (list = []) => {
      getPlanOrderDetails({list:list}).then(res => {

        let resData = res.data|| [];

        let df = {};
        let column = [];
        resData.forEach((item,index) =>{
          let encodeParams =  {label: '计划单编码', prop: "encode_"+index, width: 150, render:(params)=>{return h('div',item["encode"])}};
          let listParams =  {label: '',model: 'comm', prop: "list_"+index, labelWidth: 0, span:24, width: 150,};
          column.push(encodeParams);
          column.push(listParams);
          df["encode_"+index] = item["encode"];
          df["id_"+index] = item["id"];
          item["list"].forEach(cItem =>{
            cItem.dispatchNumberNow= cItem.unDispatchNumber;
            cItem.productionOrdersEncode= item["encode"];
          })
          df["list_"+index] = item["list"];
        })
        dispatchOpenOption.value.column = column;

        dispatchForm.value = df;

        reload.value = Math.random();
        dispatchOpen.value = true;
        console.log(resData)
      })
    }


    const selectionChange = (list) => {
      selectionList.value = list;
      multiple.value =!(selectionList.value.length > 0)

    }
    const handleBatchDispatch = () => {
      let list = selectionList.value.map(item =>{
        return {id: item.id ,encode:item.encode}
      })
      postGetPlanOrderDetails(list);
    }


    const dispatchSave = ()=>{
      let strings = Object.keys(dispatchForm.value);
      let request = [];
      strings.forEach(item =>{
        if (item.indexOf("list") !== -1){
          let list = dispatchForm.value[item].map(cItem =>{
            if (cItem.dispatchNumberNow > 0){
              return {
                productionOrdersDetailedId: cItem.id,
                dispatchNumber: cItem.dispatchNumberNow,
                productionOrdersEncode: cItem.productionOrdersEncode,
                productEncode: cItem.productEncode,
              }
            }
          })
          request = request.concat(list);
        }
      })
      if (request.length ===0){
        proxy.$message({
          type: "error",
          message: "请至少输入一条派工数量!"
        });
        return;
      }
      addDispatch(request).then(res=>{
        proxy.$message({
          type: "success",
          message: "派工成功!"
        });
        dispatchOpen.value = false;
      })
    }

    return {
      reload,
      option,
      formOption,
      dispatchOpenOption,
      dispatchTableOption,
      dialog,
      dispatchOpen,
      dialogTitle,
      loading,
      data,
      page,
      form,
      dispatchForm,
      queryParams,
      formRef,
      dispatchRef,
      multiple,
      onLoad,
      rowSave,
      dispatchSave,
      rowUpdate,
      rowDel,
      refreshChange,
      searchChange,
      handleAdd,
      handleEdit,tagStatus,tagIsUrgent,
      handleView,
      handleClose,
      handleDispatch,
      selectionChange,
      handleBatchDispatch,
    }
  }
}
</script>
<style scoped>
 ::v-deep(.avue-dialog .el-dialog__body){
   overflow: auto;
 }
</style>
